<template>
    <div class="mapView">
        <mapContainer v-if="showMap" @mapReady="ready"></mapContainer>
        <!-- 图例 -->
        <div class="legendBox">
            <div class="legend-item" v-for="(item, index) in tabList" :key="item.id">
                <img :src="item.imgUrl" alt="" :class="[index == 0 ? 'img1' : 'img2']" /> <span>{{ item.name }}</span>
            </div>
        </div>
        <div class="mapTool" v-if="currentTack">
            <el-button type="primary" @click="doOperation('开始')"> 播放</el-button>
            <!-- <el-button type="primary" @click="doOperation('重置')"> 重置</el-button> -->
        </div>
    </div>
</template>

<script setup>
import { vehicleGps, vehicleHistory } from "@/api/cleanRoute"
import { formatDate, formatDate2 } from "@/utils/tool"
import dakaLegend from "@/assets/images/dakalegend.png"
import carLegend from "@/assets/images/carLegend.png"
import shopActive from "@/assets/images/activeshop.png"
import activecar from "@/assets/images/activecar.png"
import shop from "@/assets/images/shop.png"
import car from "@/assets/images/commonCar.png"
import close from "@/assets/images/close.png"
import carTrack from "@/assets/images/carTrack.png"
import infoarrow from "@/assets/images/infoarrow.png"
import daka from "@/assets/images/daka.png"
import dayjs from "dayjs"
const props = defineProps({
    shopData: {
        type: Array
    },
    params: {
        type: Object
    }
})

function CreatetackAndPoint() {
    mapIns.clearMap()
    doTarck()
    createCleanedPoint()
}

watch(() => props.shopData, (newV) => {
    if (currentTack.value) {
        if (dakaMap.value.length > 0) {
            dakaMap.value.forEach(item => {
                item.remove()
            })
        }
        doOperation("重置")
        CreatetackAndPoint()
    }
}, {
    deep: true
})
const showMap = ref(false)
let mapIns = null
let tabList = [
    {
        id: 1,
        name: '收运车',
        imgUrl: carTrack
    },
    {
        id: 2,
        name: '打卡位置',
        imgUrl: dakaLegend
    },
]
function ready(map) {
    mapIns = map
    nextTick(() => {
        CreatetackAndPoint()
    })
}
let markerMap = ref([])

// 关闭弹框
function closeWindow() {
    let dom = document.getElementById('info-window')
    if (dom) {
        dom.remove()
        resetIcon(new AMap.Icon({
            size: [30, 35],
            image: car,
            imageSize: [30, 35]
        }))
    }
}
// 垃圾清运的逻辑
let lineArr = ref([])
let currentTack = ref(null)
// 创建点位以及轨迹的位置
async function doTarck() {
    //请求当前车的轨迹,添加轨迹线段
    let dateRange = {
        plate: '沪ABL7815',
        datefrom: "",
        dateto: ""
    }
    if (props.params.time == 'am') {
        dateRange.datefrom = dayjs(props.params.date).startOf('date').format("YYYY-MM-DD  HH:mm:ss")
        dateRange.dateto = dayjs(props.params.date).startOf('date').add(12, 'hour').format("YYYY-MM-DD  HH:mm:ss")
    } else if (props.params.time == 'pm') {
        dateRange.datefrom = dayjs(props.params.date).startOf('date').add(12, 'hour').format("YYYY-MM-DD  HH:mm:ss")
        dateRange.dateto = dayjs(props.params.date).endOf('date').format("YYYY-MM-DD  HH:mm:ss")
    }
    vehicleHistory(dateRange).then((res) => {
        if (res.code == 200) {
            if (res.data.length > 0) {
                //先清空地图上所有的标记
                lineArr.value = res.data.map((item) => {
                    return [item.lon, item.lat]
                })
                let polyline = new AMap.Polyline({
                    path: lineArr.value,
                    showDir: true,
                    strokeColor: "#28F",  //线颜色
                    // strokeOpacity: 1,     //线透明度
                    strokeWeight: 6,      //线宽
                    // strokeStyle: "solid"  //线样式
                });
                let passedPolyline = new AMap.Polyline({
                    strokeColor: "#AF5",  //线颜色
                    strokeWeight: 6,      //线宽
                });
                mapIns.add(polyline)
                mapIns.add(passedPolyline)
                mapIns.setFitView([polyline])
                //3.创建点,取第一个点作为起始位置
                const [lng, lat] = lineArr.value[0]
                let carTrackPoint = new AMap.Marker({
                    position: new AMap.LngLat(lng, lat),
                    // label: {
                    //     content: item.name,
                    //     direction: 'bottom'
                    // },
                    // 将一张图片的地址设置为 icon
                    icon: new AMap.Icon({
                        size: [13, 26],
                        image: carTrack,
                        imageSize: [13, 26]
                    }),
                    // 这个一定要添加，方式缩放的时候点位偏移，x表示图片宽度的一半 y表示图片的高，整体取负值
                    offset: new AMap.Pixel(-7, -13),
                })
                currentTack.value = carTrackPoint
                mapIns.add(carTrackPoint)
                // 4.添加点击事件和移动
                carTrackPoint.on('moving', (e) => {
                    passedPolyline.setPath(e.passedPath);
                    // mapIns.setCenter(e.target.getPosition(), true)
                })
                // 开始动画
                // nextTick(() => {
                //     doOperation('开始')
                // })
            } else {
                ElMessage.error('今日暂无轨迹数据');
            }

        }
    })
}
// 做动作
function doOperation(type) {
    switch (type) {
        case '开始':
            createCleanedPoint()
            currentTack.value.moveAlong(lineArr.value, {
                // 每一段的时长
                duration: 500,//可根据实际采集时间间隔设置
                // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
                autoRotation: true,
            });
            break;
        case '重置':
            if (currentTack.value) {
                currentTack.value.pauseMove()
                // mapIns.remove(currentTack.value)
                // mapIns.clearMap();
                // currentTack.value = null
            }
            break;
        default:
            break;
    }
}
const dakaMap = ref([])
//创建已清运的打卡点
function createCleanedPoint() {
    props.shopData.forEach((item) => {
        let marker = new AMap.Marker({
            map: mapIns,
            position: [item.lon, item.lat],
            icon: new AMap.Icon({
                size: [30, 35],
                image: daka,
                imageSize: [30, 35]
            }),
            // 这个一定要添加，方式缩放的时候点位偏移，x表示图片宽度的一半 y表示图片的高，整体取负值
            offset: new AMap.Pixel(-15, -35)
            // 114.125181.22.607298
        });
        dakaMap.value.push(marker)
        marker.on('click', (e) => {
            createInfoDakaWindow(item).open(mapIns, marker.getPosition())
            // 给弹框的关闭按钮添加点击事件，关闭弹窗
            document.getElementById('info-close').onclick = () => {
                closeWindow()
            }
        })
    })
}
function createInfoDakaWindow(item) {
    let info = {
        垃圾类别: item.type,
        收运数量: item['实际桶数'] + '桶' + item['实际重量'] + 'kg',
        收运时间: item.realtime,
        收运人员: item.worker,
        收运坐标: item.lon + ',' + item.lat
    }
    let contentStr = ""
    for (let key in info) {
        contentStr += ` <div class="basic-info"> <span class="label"> ${key}: <span class="value">${info[key]}</span>  <span/> </div>`
    }
    //   <img src="${markerInfo}" /> 
    let infoBox =
        `
      <div class="info-wrap" id="info-window">
            <div class="info-title"> 
                <div class="title-wrap">
                    <div class="title">${item['店铺名']}</div>
                    <div class="icon" id="info-close">
                        <img src="${close}" /> 
                    </div>    
                </div>
            </div>
            <div class="content" style="width:280px">
                ${contentStr}
            </div>
           
      </div>
    `
    return new AMap.InfoWindow({
        isCustom: true,
        content: infoBox,
        offset: [0, -45]
    })
}

// 重置商店选中的图片
function resetIcon(Icon) {
    markerMap.value.forEach((item) => {
        item.setIcon(Icon)
    })
}

defineExpose({
    createCleanedPoint
})



onMounted(() => {
    setTimeout(() => {
        showMap.value = true
    }, 1000)
})

</script>
<style>
.info-wrap {
    position: relative;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 4px;
    overflow: hidden;
}

.info-wrap>.info-title {
    height: 44px;
    background: linear-gradient(180deg, rgba(156, 224, 255, 0.95) 0%, rgba(255, 255, 255, 0.95) 100%), rgba(255, 255, 255, 1);
}

.info-wrap>.info-title>.title-wrap {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;

    justify-content: space-between;
    padding: 0 14px;
    box-sizing: border-box;
    font-weight: bold;

}

.info-title>.title {
    color: rgba(51, 51, 51, 1);
}

.info-title>.title-wrap>.icon {
    cursor: pointer;
}

.info-title>.title-wrap>.icon img {
    width: 12px;
    height: 12px;
}

.info-wrap>.line {
    margin: 15px 0;
    width: 100%;
    height: 1px;
    background: rgba(239, 239, 239, 1);
}

.basic-info {
    margin: 5px 15px;
}

.basic-info .label {
    color: rgba(128, 128, 128, 1);
}

.basic-info .value {
    color: rgba(51, 51, 51, 1);
}

.amap-info-contentContainer {
    position: relative;
}

.info-arrow {
    position: absolute;
    bottom: -30px;
    left: 50%;
    transform: translateX(-50%);

}

.info-arrow>img {
    width: 30px;
    height: 18px;
}

.amap-marker-label {
    border: unset;
    background: unset;
}
</style>
<style lang="scss" scoped>
.mapView {
    position: relative;
    height: 100%;
    width: 100%;


    .legendBox {
        background: #fff;
        border-radius: 10px;
        padding: 10px;
        position: absolute;
        top: 20px;
        left: 20px;
        z-index: 10;

        .legend-item {
            display: flex;
            align-items: center;
            // justify-content: space-between;
            // font-size: 26px;
            color: rgba(51, 51, 51, 1);
            margin-bottom: 10px;

            .img1 {
                width: 20px;
                // height: 15px;
            }

            .img2 {
                width: 30px;
                height: 30px;
            }

            span {
                margin-top: 5px;
            }
        }
    }

    .mapTool {
        background: #fff;
        border-radius: 10px;
        padding: 10px;
        position: absolute;
        top: 20px;
        right: 20px;
        z-index: 10;
    }

}
</style>